package com.jdy.haoduoaiteacher.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupMenu;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.activity.AddHabitClockActivity;
import com.jdy.haoduoaiteacher.activity.BaseActivity;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.HabitPlan;
import com.jdy.haoduoaiteacher.model.LeHabitPlanRecordWrapper;
import com.jdy.haoduoaiteacher.model.LeMachine;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.PainPointItem;
import com.jdy.haoduoaiteacher.util.CommonUtil;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.NoScrollListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.ycsj.goldmedalnewconcept.R;

import java.util.ArrayList;
import java.util.HashMap;

import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;

import static com.jdy.haoduoaiteacher.util.Tools.getWeek;

/**
 * @author hf
 */
public class RecentPlayAdapter extends BaseAdapter implements
        StickyListHeadersAdapter, SectionIndexer {

    private ArrayList<LeHabitPlanRecordWrapper> mList;
    private LePlaybackRecordWrapperAdapter adapter;
    @SuppressWarnings("unused")
    private final DisplayImageOptions options;
    private DisplayMetrics dm;
    private LayoutParams params;
    private final float NUM = (float) 3.5; // 每行显示个数
    private final float LIEWIDTH;// 每列宽度
    private LeUser mLeUser;
    private LeMachine mLeMachine;

    private final BaseActivity mContext;
    private int[] mSectionIndices;
    private String[] mSectionLetters;
    private LayoutInflater mInflater;

    public void setData(ArrayList<LeHabitPlanRecordWrapper> listdata) {
        this.mList = listdata;
    }


    public View getSelectView() {
        return mSelView;
    }

    private View mSelView;

    private int highLightPosition = -1; // 正在播放

    public int getHighLightPosition() {
        return highLightPosition;
    }

    public void setHighLightPosition(int highLightPosition) {
        this.highLightPosition = highLightPosition;
        notifyDataSetChanged();
    }

    public RecentPlayAdapter(BaseActivity context,
                             ArrayList<LeHabitPlanRecordWrapper> list) {
        mContext = context;

        this.mList = list;
        mInflater = LayoutInflater.from(context);
        mSectionIndices = getSectionIndices();
        mSectionLetters = getSectionLetters();

        mInflater = LayoutInflater.from(mContext);
        dm = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
        LIEWIDTH = dm.widthPixels / NUM;

        mLeMachine = MyTeacherApp.getInstance().getBabyTeacher();

        if (mLeMachine == null) {
            mLeUser = MyTeacherApp.getInstance().getUserTeacher();
            if (mLeUser != null) {
                mLeMachine = mLeUser.machine;
            }
        }

        // 用 displayImage 加载图片 的 配置参数
        options = new DisplayImageOptions.Builder()
                .showImageOnFail(R.drawable.default_img_listitem) // 下载 失败 显示的 图片
                .cacheInMemory(true) // 缓存
                .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
                .build();
        // 创建默认的ImageLoader配置参数
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
                mContext).writeDebugLogs() // 打印 log 信息
                .build();
        ImageLoader.getInstance().init(configuration);
    }

    private int[] getSectionIndices() {
        int[] sections = new int[mList.size()];
        for (int i = 0; i < mList.size(); i++) {
            sections[i] = i;
        }
        return sections;
    }

    private String[] getSectionLetters() {
        String[] letters = new String[mList.size()];
        for (int i = 0; i < mList.size(); i++) {
            letters[i] = mList.get(i).dateTag;
        }
        return letters;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private void setListener(ViewHolder holder, LeHabitPlanRecordWrapper to) {
        if (null != holder) {
            holder.listView.setTag(to);
        }
    }

    private Dialog notificationTipDlg;

    public void showPopMenu(View view) {
        PopupMenu menu = new PopupMenu(mContext, view);
        menu.getMenuInflater().inflate(R.menu.main_menu, menu.getMenu());
        menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
//          case R.id.add_item:
//           // Toast.makeText(MainActivity.this, "Add selected", Toast.LENGTH_SHORT).show();
//            break;

                    case R.id.delete_item:
                        //  Toast.makeText(MainActivity.this, "Delete Selected", Toast.LENGTH_SHORT).show();
                        break;

                }
                return true;
            }
        });
        menu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                //  Toast.makeText(MainActivity.this, "关闭了", Toast.LENGTH_SHORT).show();
            }
        });
        menu.show();
    }

    private SparseArray<View> cvArray = new SparseArray<>();

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LeHabitPlanRecordWrapper menuItemVo = mList.get(position);
        ViewHolder holder;

        convertView = cvArray.get(position);

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.recent_playbacklist_item_teacher, null);

            holder.titleText = (TextView) convertView.findViewById(R.id.titleText);

            holder.listView = (NoScrollListView) convertView
                    .findViewById(R.id.listview);

            holder.linearLayout1 = convertView.findViewById(R.id.linearLayout1);

            convertView.setTag(holder);

            cvArray.put(position, convertView);

            setListener(holder, menuItemVo);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (highLightPosition >= 0 && highLightPosition == position) {
            holder.linearLayout1.setBackgroundColor(0x88fcf5da);
            // mSelView = holder.rela_parent;
        } else {
            holder.linearLayout1.setBackgroundColor(Color.TRANSPARENT);
        }

        adapter = new LePlaybackRecordWrapperAdapter(mContext, menuItemVo.list,
                menuItemVo.dateTag);
        holder.titleText.setText(menuItemVo.dateTag);
        holder.listView.setAdapter(adapter);

        params = new LayoutParams((int) (adapter.getCount() * (LIEWIDTH)),
                LayoutParams.WRAP_CONTENT);

        holder.listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, View view, final int subposition, long id) {

                // showPopMenu(holder.listView);


                LayoutInflater inflater = mContext.getLayoutInflater();
                final View layout = inflater.inflate(R.layout.delete_item, null);// 获取自定义布局
                Button positiveButton = (Button) layout.findViewById(R.id.positiveButton);
                Button negativeButton = (Button) layout.findViewById(R.id.negativeButton);

                positiveButton.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
                positiveButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        if (notificationTipDlg != null) {
                            notificationTipDlg.dismiss();
                            notificationTipDlg = null;
                        }

                        LeHabitPlanRecordWrapper item = (LeHabitPlanRecordWrapper) parent
                                .getTag();

                        if (item != null) {
                            final HabitPlan subItem = mList.get(position).list.get(subposition);

                            new CustomAsyncTask(mContext, new IAsyncTask() {
                                @Override
                                public void onRecieveData(Activity activity,
                                                          ResponseResult result) {
                                    if (result.isSuccess()) {
                                        Toast.makeText(mContext, "删除成功",
                                                Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent("updatehabit");
                                        mContext.sendBroadcast(intent);
                                    } else {
                                        if (Tools.isNotNullStr(result.data)) {
                                            Toast.makeText(mContext, result.data,
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }

                                @Override
                                public ResponseResult doInbackground(Activity activity) {
                                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                                    LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                                    if (lu == null) {
                                        lu = Tools.restoreLeUser();
                                    }

                                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);

                                    return HttpUtils.startRequest(HttpUtils.API_URL
                                                    + "/api/2.0/operation/habit/habits_teacher/"
                                                    + subItem.id, param_,
                                            HttpUtils.TAG_DELETE_REQUEST);
                                }
                            }).execute();

                        }
                    }
                });


                negativeButton.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
                negativeButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        if (notificationTipDlg != null) {
                            notificationTipDlg.dismiss();
                            notificationTipDlg = null;
                        }
                    }
                });

                notificationTipDlg = new Dialog(mContext, R.style.custom_dialog);
                notificationTipDlg.setContentView(layout);
                notificationTipDlg.setCancelable(true);
                notificationTipDlg.show();

//        PopDeleteWindow popWindow = new PopDeleteWindow(mContext);
//        popWindow.setOnMenuClickListener(new PopDeleteWindow.OnMenuClickListener() {
//          @Override
//          public void onClickShare() {
//
//          }
//
//          @Override
//          public void onClickDelete() {
//
//
//
//
//
//          }
//
//          @Override
//          public void onClickCancel() {
//
//          }
//        });
//       // popWindow.showPopupWindow(view);
//
//
//        if (!popWindow.isShowing()) {
//
//          int[] location = new int[2];
//          view.getLocationOnScreen(location);
//
//          popWindow.showAtLocation(view, Gravity.CENTER, location[0], 0);
//
//          // 以下拉方式显示popupwindow
//         // popWindow.showAsDropDown(view, view.getLayoutParams().width / 2, 5);
//        } else {
//          popWindow.dismiss();
//        }

                return true;
            }
        });

        holder.listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int subposition,
                                    long id) {

                LeHabitPlanRecordWrapper item = (LeHabitPlanRecordWrapper) parent
                        .getTag();


                if (item != null) {
                    HabitPlan subItem = mList.get(position).list.get(subposition);

                    Intent intent = new Intent();
                    intent.setClass(mContext, AddHabitClockActivity.class);
                    intent.putExtra("isedit", true);

                    PainPointItem item2 = new PainPointItem();
                    item2.id = subItem.id;
                    item2.img = subItem.img;
                    item2.name = subItem.name;
                    item2.time = subItem.time;
                    item2.date_from = subItem.date_from;
                    item2.date_to = subItem.date_to;
                    item2.enable = 1;
                    item2.macid = subItem.macid;
                    item2.mp3_url = subItem.mp3_url;

                    item2.emc = subItem.emc;
                    item2.ctype = subItem.ctype;
                    item2.info_img = subItem.info_img;
                    item2.info_title = subItem.info_title;
                    item2.info_desc = subItem.info_desc;


                    intent.putExtra("custompainpoint", item2);
                    mContext.startActivity(intent);
                }

            }
        });

        return convertView;

    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        HeaderViewHolder holder;

        if (convertView == null) {
            holder = new HeaderViewHolder();
            convertView = mInflater.inflate(R.layout.header, parent, false);
            holder.text = (TextView) convertView.findViewById(R.id.text1);
            holder.root_view = convertView.findViewById(R.id.root_view);
            convertView.setTag(holder);
        } else {
            holder = (HeaderViewHolder) convertView.getTag();
        }

        // set header text as first char in name
        // CharSequence headerChar = mCountries[position].subSequence(0, 1);
        holder.root_view.setVisibility(View.VISIBLE);
        LeHabitPlanRecordWrapper menuItemVo = mList.get(position);

        holder.text.setText(getWeek(menuItemVo.dateTag) + " " + menuItemVo.dateTag.substring(0, 4)
                + "年" + menuItemVo.dateTag.substring(5, 7) + "月" + menuItemVo.dateTag.substring(8, menuItemVo.dateTag.length()) + "日");

        return convertView;
    }

    /**
     * Remember that these have to be static, postion=1 should always return the
     * same Id that is.
     */
    @Override
    public long getHeaderId(int position) {

        LeHabitPlanRecordWrapper menuItemVo = mList.get(position);
        return menuItemVo.hashCode();
    }

    @Override
    public int getPositionForSection(int section) {
        if (mSectionIndices.length == 0) {
            return 0;
        }

        if (section >= mSectionIndices.length) {
            section = mSectionIndices.length - 1;
        } else if (section < 0) {
            section = 0;
        }
        return mSectionIndices[section];
    }

    @Override
    public int getSectionForPosition(int position) {
        for (int i = 0; i < mSectionIndices.length; i++) {
            if (position < mSectionIndices[i]) {
                return i - 1;
            }
        }
        return mSectionIndices.length - 1;
    }

    @Override
    public Object[] getSections() {
        return mSectionLetters;
    }


    class HeaderViewHolder {
        TextView text;
        View root_view;
    }

    private static class ViewHolder {
        public TextView titleText;
        private TextView view_more;
        public NoScrollListView listView;
        public ImageButton pushbtn;
        public View linearLayout1;
    }

}
